package com.xcy.quickhand.util.redis;

import com.xcy.quickhand.Constant;
import com.xcy.quickhand.model.Video;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2023/2/11 23:27
 */
public class RedisUtil {

    RedisTemplate redisTemplate;

    public RedisUtil(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 管道方式存入map类型数据到redis中，如果key重复保存，则只会对value进行更新，不会额外加入一条记录到redis
     * @param key
     * @param hashValues
     */
    public void pipeLineHashData(String key, Map<String, String> hashValues) {

        if (StringUtils.isEmpty(key) || CollectionUtils.isEmpty(hashValues)) {
            return;
        }
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        RedisSerializer<String> keySerializer = redisTemplate.getKeySerializer();
        RedisSerializer<String> valueSerializer = redisTemplate.getValueSerializer();


        redisTemplate.executePipelined((RedisCallback<Object>) pipeLine -> {
            try {
                hashValues.entrySet().forEach(entry -> {
                    pipeLine.hSet(keySerializer.serialize(key), keySerializer.serialize(entry.getKey()), valueSerializer.serialize(entry.getValue()));
                });
            } catch (Exception e) {
                //log.error("设置redis缓存异常: {}", e.getMessage());
                e.printStackTrace();
            }
            return null;
        });
    }


    /**
     * 批量根据key查询value
     * @param key
     * @param hashValues
     * @return
     */
    public List<String> getPipeLineHashData(String key, List<String> hashValues) {
        if (StringUtils.isEmpty(key) || CollectionUtils.isEmpty(hashValues)) {
            return null;
        }
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        RedisSerializer<String> keySerializer = redisTemplate.getKeySerializer();
        RedisSerializer<String> valueSerializer = redisTemplate.getValueSerializer();
        List<String> values = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                hashValues.forEach(phone -> {
                    redisConnection.hGet(keySerializer.serialize(key), valueSerializer.serialize(phone));
                });
                return null;
            }
        }, redisTemplate.getValueSerializer());
        return values;
    }

    /**
     * 获取redis缓存过的视频（不需要在保存到数据中）
     **/
    public List<String> getRedisVehicleCacheByPlateNumber(List<Video> videoList) {
        if (CollectionUtils.isEmpty(videoList)) {
            return null;
        }
        List<String> list = videoList.stream()
                .map(v -> v.getAuthorId() + "_" + v.getVideoId()).collect(Collectors.toList());
        return getPipeLineHashData(Constant.VIDEO_URL, list);
    }
}
